﻿#ifdef WIN32
#include <Windows.h>
#include <windowsx.h>
#include <winbase.h>
#endif


#include "main_widget.h"
#include "web_class.h"
#include <qapplication.h>
#include <qdesktopwidget.h>
#include <QDebug>
#include "close_dialog.h"
#include <QScreen>
#include <QNetworkInterface>
#include <QDomDocument>
#include <QNetworkAccessManager>
#include <QEventLoop>
#include <QNetworkReply>
#include <QFileDialog>
#include "crash.h"
using namespace std;







MainWidget::MainWidget(QWidget* parent)
    : QWidget(parent),
    is_full_(false),
    is_max_(true),
    web_debug_(false)
{
#if defined(Q_OS_WIN32)
    SetUnhandledExceptionFilter(Debug::crashStackCallback);
#endif
    QFileDialog dialog;
    dialog.setViewMode(QFileDialog::Detail); // 设置为多选
    dialog.setFileMode(QFileDialog::ExistingFiles); // 设置为多选
    dialog.setOption(QFileDialog::DontUseNativeDialog); // 使用Qt自己的对话框
  

    auto win_point = QApplication::desktop()->screenGeometry();
    qDebug() << "w=" << win_point.width() << ",h=" << win_point.height();
   
    window_width_ = 1080;
    window_height_ = 720;

    QString inipath = QCoreApplication::applicationDirPath() + "/conf/config.ini";


    setting_ = new QSettings(inipath, QSettings::IniFormat, this);
    setting_->setIniCodec(QTextCodec::codecForName("UTF-8"));

    QString web_debug = setting_->value("sys/web_debug", "").toString();
    load_url_ = setting_->value("sys/load_url", QCoreApplication::applicationDirPath() + "/xuding/index.html").toString();

    if (web_debug == "paradise") {
        web_debug_ = true;
    }
    
    qputenv("QTWEBENGINE_DISABLE_SANDBOX", "1");

    qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--disable-web-security");

    //qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--user-data-dir");
    //qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--enable-logging --v=1");

   
    if (web_debug_)
        qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "9301");

#ifdef WIN32
    setWindowFlags(Qt::FramelessWindowHint|Qt::WindowSystemMenuHint|Qt::WindowMinimizeButtonHint|Qt::WindowMaximizeButtonHint);
#endif
    
    setMinimumSize(QSize(window_width_, window_height_));
    setWindowIcon(QIcon(":/img/logo.ico"));
    setObjectName("MainWidget");
 



    QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
    QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::ScreenCaptureEnabled, true);
    QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);
    QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::WebGLEnabled, true);
    //QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
    //QWebEngineSettings::defaultSettings()->setAttribute(QWebEngineSettings::AllowWindowActivationFromJavaScript, true);

    custom_page_ = new CustomPage;
    connect(custom_page_, &CustomPage::featurePermissionRequested, this, &MainWidget::onFeaturePermissionRequestedSlot);

    central_widget = new QWidget(this);
    title_widget = new QWidget(this);
    central_widget->setObjectName("central_widget");
    title_widget->setObjectName("title_widget");
  
    title_widget->setFixedHeight(30);

    connect(this, &MainWidget::service_inited_sig, this, &MainWidget::service_inited_slot, Qt::QueuedConnection);

    webview_ = new QWebEngineView(central_widget);
    webview_->setContextMenuPolicy(Qt::NoContextMenu);
    
    webview_->setPage(custom_page_);

   

    
    bool full_screen = setting_->value("basic/full_screen", false).toBool();


    //QString html_path = QCoreApplication::applicationDirPath()+"/html/webrtc.html";
    //QString html_path ="D:/work/video-pc-client/video-pc-client/html/webrtc.html";

    //qDebug()<<"-------------------------------------html_path = "<<html_path;

    //webview_->setUrl(QUrl("file:///"+html_path));
    //webview_->setUrl(QUrl("https://127.0.0.1:9001/html/webrtc.html"));
    //webview_->setUrl(QUrl("https://172.16.100.135:8890/#/join-meeting"));
    //webview_->setUrl(QUrl("qrc:/html/webrtc.html"));

    std::set<string> localIpSet;
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    for(auto it : list)
    {
        if (it != QHostAddress::LocalHost) {
            localIpSet.insert(it.toString().toStdString());
        }
        
    }


    webchannel_ = new QWebChannel(this);
    web_class_ = new WebClass(this);

    web_class_->meeting_service_->init(QDir::homePath().toStdString(),QCoreApplication::applicationDirPath().toStdString(), localIpSet,std::bind(&MainWidget::on_service_inited, this, std::placeholders::_1));
    webchannel_->registerObject("webobj", web_class_);
   
    webview_->page()->setWebChannel(webchannel_);


   /* systemtrayicon_ = new QSystemTrayIcon(this);
    systemtrayicon_->setIcon(QIcon(":/img/logo.ico"));
    systemtrayicon_->setToolTip(QString::fromLocal8Bit("muti-meeting"));
    connect(systemtrayicon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(slot_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
    createMenu();
    systemtrayicon_->show();*/

    closebtn_ = new Button(central_widget);
    closebtn_->setFixedSize(QSize(46, 30));
    closebtn_->setCursor(Qt::PointingHandCursor);
    closebtn_->setToolTip(QString::fromLocal8Bit("关闭"));
    closebtn_->setObjectName("close_btn");

    QPixmap close_pixmap(":/img/close.png");
    close_pixmap = close_pixmap.scaled(16, 16, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    closebtn_->setIcon(close_pixmap);

   

    connect(closebtn_, &QPushButton::clicked, this, &MainWidget::on_close_btn_clicked);

    maxbtn_ = new Button(central_widget);
    maxbtn_->setFixedSize(QSize(46, 30));
    maxbtn_->setCursor(Qt::PointingHandCursor);
    maxbtn_->setToolTip(QString::fromLocal8Bit("最大化"));
    maxbtn_->setObjectName("max_btn");

    max_pixmap_ = QPixmap(":/img/max.png");
    max_pixmap_ = max_pixmap_.scaled(16, 16, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    normal_pixmap_ = QPixmap(":/img/normal.png");
    normal_pixmap_ = normal_pixmap_.scaled(16, 16, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    maxbtn_->setIcon(normal_pixmap_);


   

    connect(maxbtn_, &QPushButton::clicked, this, [&]() {
        if (is_max_) {

            user_show_normal();
        }
        else {
            user_show_max();

        }
    });

    minbtn_ = new Button(central_widget);
    minbtn_->setFixedSize(QSize(46, 30));
    minbtn_->setCursor(Qt::PointingHandCursor);
    minbtn_->setToolTip(QString::fromLocal8Bit("最小化"));
    minbtn_->setObjectName("min_btn");

    QPixmap min_pixmap(":/img/min.png");

    min_pixmap = min_pixmap.scaled(16, 16, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    minbtn_->setIcon(min_pixmap);
    
    connect(minbtn_, &QPushButton::clicked, this, [this]() {
        showMinimized();

    });


    fullbtn_ = new Button(central_widget);
    fullbtn_->setFixedSize(QSize(46, 30));
    fullbtn_->setCursor(Qt::PointingHandCursor);
    fullbtn_->setToolTip(QString::fromLocal8Bit("全屏"));
    fullbtn_->setObjectName("full_btn");

    QPixmap full_pixmap(":/img/full_screen.png");
    full_pixmap = full_pixmap.scaled(16, 16, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    fullbtn_->setIcon(full_pixmap);
    
    connect(fullbtn_, &QPushButton::clicked, this, &MainWidget::switch_full);



    logo_label_ = new QLabel(this);
    logo_label_->setFixedSize(QSize(20, 20));
    QPixmap pixmap(":/img/logo.ico");
    pixmap = pixmap.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    
    logo_label_->setPixmap(pixmap);


    title_label_ = new QLabel(this);
    title_label_->setFixedSize(QSize(80, 20));
    title_label_->setObjectName("title_label");
    title_label_->setText(QString::fromLocal8Bit("专业会议控制"));
    title_label_->setContentsMargins(5, 0, 0, 0);

    version_label_ = new QLabel(this);
    version_label_->setFixedSize(QSize(80, 20));
    version_label_->setObjectName("version_label");
    version_label_->setContentsMargins(5, 0, 0, 0);
    show_version();
    QHBoxLayout* barlayout = new QHBoxLayout();

    barlayout->addWidget(logo_label_);
    barlayout->addWidget(title_label_);
    barlayout->addWidget(version_label_);
    barlayout->addStretch();
    barlayout->addWidget(fullbtn_);
    barlayout->addWidget(minbtn_);
    barlayout->addWidget(maxbtn_);
    barlayout->addWidget(closebtn_);

    barlayout->setSpacing(0);
    //barlayout->setMargin(0);
    barlayout->setContentsMargins(2,1,1,0);
    title_widget->setLayout(barlayout);
    QVBoxLayout* layout = new QVBoxLayout();

#ifdef WIN32
    layout->addWidget(title_widget);
#else
    title_widget->hide();
#endif

    layout->addWidget(webview_);
    layout->setSpacing(0);
    layout->setMargin(1);

    central_widget->setLayout(layout);
    central_widget->hide();
    QVBoxLayout* main_layout = new QVBoxLayout();
    main_layout->addWidget(central_widget);
    main_layout->setSpacing(0);
    main_layout->setMargin(0);
    setLayout(main_layout);
    //user_show_max();

    QTimer::singleShot(300ms, [&]() {
        central_widget->show();
        
    });
    if (full_screen) {
        switch_full();
    }

    QFile file(":/res/qss/main.qss");	//main.qss为文件路径
    file.open(QFile::ReadOnly);
    QTextStream filetext(&file);
    QString stylesheet = filetext.readAll();
    this->setStyleSheet(stylesheet);

    auto qpoint = QApplication::desktop()->screenGeometry();
    qDebug() << "w="<< qpoint.width()<<",h="<<qpoint.height();
    //int pr = QApplication::desktop()->devicePixelRatio();
    //qDebug() << "dotsPerInch=" << pr;
    //QScreen* screen = qApp->primaryScreen();
    //qreal    dotsPerInch = screen->logicalDotsPerInch(); /* 单位内的点数 */
    /*QList<QScreen*> screens = QApplication::screens();
    QScreen* screen = screens[0];
    qreal dpi = screen->logicalDotsPerInch();
    qDebug() << "dotsPerInch=" << dpi;*/
}

MainWidget::~MainWidget() {

}


void MainWidget::show_version()
{
    QFile verFile(QCoreApplication::applicationDirPath() + "/version.txt");

    verFile.open(QFile::ReadOnly);
    QString ver = "V1.0.0";
    if (verFile.isOpen())
    {
        ver = QString(verFile.readAll());
        verFile.close();
    }
    version_label_->setText(ver);
}

void MainWidget::switch_full()
{
    if (is_full_) {
        title_widget->show();
        showNormal();
    }
    else {
        title_widget->hide();
        showFullScreen();
    }
    is_full_ = !is_full_;
}

void MainWidget::mousePressEvent(QMouseEvent* event) {
    m_lastPos = event->globalPos();
}

void MainWidget::mouseMoveEvent(QMouseEvent* event) {
    if (is_full_) return;

    int dx = event->globalX() - m_lastPos.x();
    int dy = event->globalY() - m_lastPos.y();

    if (dx == 0 && dy == 0) return;
    m_lastPos = event->globalPos();
    if (is_max_) {
        user_show_normal(true);
    }

    move(x() + dx, y() + dy);
}



void MainWidget::keyPressEvent(QKeyEvent* event) {
    if (web_debug_) 
    {
        switch (event->key())
        {
        case Qt::Key_F5:
            webview_->reload();
            break;
        default:
            qDebug() << event->key();
            break;
        }
    }
    

    switch (event->key())
    {
    case Qt::Key_F11:
        switch_full();
        break;
    case Qt::Key_Escape:
        if(is_full_) switch_full();
        break;
    }


}

#ifdef WIN32
bool MainWidget::nativeEvent(const QByteArray& eventType, void* message, long* result)
{
    if (eventType == "windows_generic_MSG")
    {
        PMSG msg = (PMSG)message;
        if (msg->message == WM_USER + 15396)
        {
            show();
        }

    }
    return false;
 
}
#endif

void MainWidget::onFeaturePermissionRequestedSlot(const QUrl& securityOrigin, QWebEnginePage::Feature feature)
{
    qDebug() << "&CustomWebEnginePage::featurePermissionRequested";
    webview_->page()->setFeaturePermission(securityOrigin, feature, QWebEnginePage::PermissionGrantedByUser);

}

void MainWidget::user_show_normal(bool is_hit)
{
    int index = QApplication::desktop()->screenNumber(this);
    QRect rect = QApplication::desktop()->availableGeometry(index);
    int left=0, top = 0;
    if(rect.width() > window_width_)
        left = (rect.width() - window_width_) / 2;
    if (rect.height() > window_height_)
        top = (rect.height() - window_height_) / 2;

    if (is_hit) {
        left = (m_lastPos.x()/2) ;
        top = (m_lastPos.y());
    }

    QRect srect(left, top, window_width_, window_height_);


    setGeometry(srect);
    maxbtn_->setToolTip(QString::fromLocal8Bit("最大化"));
    is_max_ = false;

    maxbtn_->setIcon(max_pixmap_);
}

void MainWidget::user_show_max()
{
    maxbtn_->setToolTip(QString::fromLocal8Bit("向下还原"));
    int index = QApplication::desktop()->screenNumber(this);
    setGeometry(QApplication::desktop()->availableGeometry(index));
    is_max_ = true;

    maxbtn_->setIcon(normal_pixmap_);
}



void MainWidget::createMenu() {
    QAction* exitappaction = new QAction(QString::fromLocal8Bit("quit"), this);

    connect(exitappaction, SIGNAL(triggered()), this, SLOT(slot_exitAppAction()));

    menu_ = new QMenu(this);
    //menu_->addAction(showmainaction);
    //menu_->addSeparator();
    menu_->addAction(exitappaction);
    //menu_->setStyleSheet("QPushButton:hover{background:#dadada;}");
    systemtrayicon_->setContextMenu(menu_);
}

void MainWidget::slot_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason) {
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        //单击托盘图标
        break;
    case QSystemTrayIcon::DoubleClick:
        //双击托盘图标
        //双击后显示主程序窗口
        this->show();
        break;
    default:
        break;
    }
}

void MainWidget::slot_exitAppAction() {
    this->close();
}



void MainWidget::on_close_btn_clicked()
{

	close_dia_ = new close_dialog(this);

	connect(close_dia_, &QDialog::accepted, this, &MainWidget::on_close_diglog_accept);
	connect(close_dia_, &QDialog::finished, this, &MainWidget::on_close_diglog_finish);

	QPoint p = this->pos();

	close_dia_->setGeometry(this->width() + p.x() - 230, p.y() + 40, 220, 160);

	close_dia_->exec();
    


}



void MainWidget::on_close_diglog_accept()
{
    
   this->close();
   
}

void MainWidget::on_close_diglog_finish()
{
    delete close_dia_;
    close_dia_ = nullptr;
    qDebug() << "on_close_diglog_accept";
}


void MainWidget::on_service_inited(int port)
{
    http_port_ = port;
    emit service_inited_sig();

}

void MainWidget::service_inited_slot()
{
    QString prifix = "#/?http_port=" + QString::number(http_port_);
    qDebug() << "url = "<< load_url_ + prifix;

    webview_->setUrl(QUrl(load_url_+ prifix));

    connect(webview_->page(), &QWebEnginePage::featurePermissionRequested, this, &MainWidget::onFeaturePermissionRequestedSlot);

    webchannel_->registerObject("webobj", web_class_);
    webview_->page()->setWebChannel(webchannel_);
}

/////////////////////////////////

Button::Button(QWidget* parent)
{

}

void Button::mousePressEvent(QMouseEvent* event) {
    ismove = false;
    click_pos = event->pos();
}

void Button::mouseMoveEvent(QMouseEvent* event) {
    if (qAbs(click_pos.x() - event->pos().x()) > 30 ||
        qAbs(click_pos.y() - event->pos().y()) > 30) {
        ismove = true;
    }
}

void Button::mouseReleaseEvent(QMouseEvent* event) {
    if (!ismove) {
        emit clicked();
    }
}

